package sm.dbdict;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import sm.dam.api.Converter;
import sm.util.Util;

public class DBDictChangePolicy {
	private boolean ignoreFieldChange = false;

	private boolean ignoreUniqueKey = false;

	private List<String> ignoreFieldChanges = new ArrayList<String>();

	private List<String> ignoreUniqueKeys = new ArrayList<String>();

	private Map<String, Map<String, Converter>> converters = new HashMap<String, Map<String, Converter>>();

	public void setConverters(Map<String, Converter> configConverters) {
		for (Entry<String, Converter> entry : configConverters.entrySet()) {
			String key = entry.getKey();
			Converter converter = entry.getValue();
			int fileNameIdx = key.indexOf(",");
			if (fileNameIdx != -1) {
				String fileName = key.substring(0, fileNameIdx);
				fileName = Util.radEntityNameToJava(fileName);
				String fieldPath = key.substring(fileNameIdx + 1);
				fieldPath = Util.radFieldPathToJava(fieldPath);
				Map<String, Converter> fileConverters = converters
						.get(fileName);
				if (fileConverters == null) {
					fileConverters = new HashMap<String, Converter>();
					converters.put(fileName, fileConverters);
				}
				fileConverters.put(fieldPath, converter);
			}
		}
	}

	public void setIgnoreFieldChange(boolean ignoreFieldChange) {
		this.ignoreFieldChange = ignoreFieldChange;
	}

	public void setIgnoreUniqueKey(boolean ignoreUniqueKey) {
		this.ignoreUniqueKey = ignoreUniqueKey;
	}

	public void setIgnoreFieldChanges(List<String> ignoreFieldChanges) {
		this.ignoreFieldChanges = ignoreFieldChanges;
	}

	public void setIgnoreUniqueKeys(List<String> ignoreUniqueKeys) {
		this.ignoreUniqueKeys = ignoreUniqueKeys;
	}

	public boolean needIgnoreFieldChange(String fileName, String fieldPath) {
		boolean ignoreFieldChange = this.ignoreFieldChange;
		String path = fileName + "," + fieldPath;
		if (ignoreFieldChanges.contains(path)) {
			ignoreFieldChange = true;
		} else if (ignoreFieldChanges.contains(fileName)) {
			ignoreFieldChange = true;
		}
		return ignoreFieldChange;
	}

	public boolean needIgnoreUniqueKey(String fileName, String keyStr) {
		boolean ignoreNewKey = this.ignoreUniqueKey;
		String path = fileName + "," + keyStr;
		if (ignoreUniqueKeys.contains(path)) {
			ignoreNewKey = true;
		} else if (ignoreUniqueKeys.contains(fileName)) {
			ignoreNewKey = true;
		}
		return ignoreNewKey;
	}

	public Converter getConverter(String fileName, String fieldPath) {
		Converter converter = null;
		Map<String, Converter> fileConverters = converters.get(fileName);
		if (fileConverters != null) {
			converter = fileConverters.get(fieldPath);
		}

		return converter;
	}

	public Map<String, Converter> getConverters(String fileName) {
		return converters.get(fileName);
	}

}
